// cloudfunctions/shipOrder/index.js
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    console.log('开始处理发货请求', event);
    
    // 从参数获取订单ID和发货信息
    const {
      orderId,           // 订单ID
      shipMethod,        // 发货方式
      expressCompany,    // 快递公司
      expressNumber,     // 快递单号
      operatorId,        // 操作人ID
      operatorName       // 操作人姓名
    } = event;
    
    // 参数验证
    if (!orderId) {
      return {
        success: false,
        message: '订单ID不能为空'
      };
    }
    
    if (!shipMethod) {
      return {
        success: false,
        message: '请选择发货方式'
      };
    }
    
    // 如果是物流快递，验证快递公司和快递单号
    if (shipMethod === 'express' && (!expressCompany || !expressNumber)) {
      return {
        success: false,
        message: '请填写快递公司和快递单号'
      };
    }
    
    // 开始数据库事务
    const transaction = await db.startTransaction();
    
    try {
      // 1. 查询订单信息
      const orderResult = await transaction.collection('orders')
        .doc(orderId)
        .get();
      
      const order = orderResult.data;
      
      // 验证订单状态
      if (order.status != 2) {
        throw new Error(`订单状态不正确，当前状态: ${order.status}`);
      }
      
      // 2. 更新订单状态和发货信息
      await transaction.collection('orders')
        .doc(orderId)
        .update({
          data: {
            status: 3, // 已发货
            shipInfo: {
              method: shipMethod,
              expressCompany: shipMethod === 'express' ? expressCompany : '',
              expressNumber: shipMethod === 'express' ? expressNumber : '',
              shipTime: db.serverDate()
            },
            shipTime: db.serverDate()
          }
        });
      
      // 3. 生成发货记录
      await transaction.collection('shipRecords')
        .add({
          data: {
            orderId: orderId,
            orderNumber: order.outTradeNo,
            goodsId: order.goodsId,
            goodsName: order.goodsName,
            buyerId: order.buyerId,
            buyerName: order.buyerName,
            shipMethod: shipMethod,
            expressCompany: shipMethod === 'express' ? expressCompany : '',
            expressNumber: shipMethod === 'express' ? expressNumber : '',
            shipTime: db.serverDate(),
            operatorId: operatorId,
            operatorName: operatorName,
            createTime: db.serverDate()
          }
        });
      
      // 提交事务
      await transaction.commit();
      
      console.log('发货处理成功', { orderId, shipMethod });
      
      return {
        success: true,
        message: '发货成功',
        data: {
          orderId,
          shipMethod,
          expressCompany,
          expressNumber
        }
      };
      
    } catch (txError) {
      // 回滚事务
      await transaction.rollback();
      console.error('发货处理失败，已回滚', txError);
      
      return {
        success: false,
        message: '发货失败',
        error: txError.message
      };
    }
  } catch (error) {
    console.error('云函数执行失败', error);
    
    return {
      success: false,
      message: '云函数执行失败',
      error: error.message
    };
  }
};